package com.dlm.service.impl;

import com.dlm.dao.Coupon;
import com.dlm.dao.UserCoupon;
import com.dlm.service.IUserCouponService;
import com.jfinal.plugin.activerecord.Page;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by chongsong on 15/3/17.
 * song316@gmail.com
 */
public class UserCouponServiceImpl implements IUserCouponService {
    @Override
    public boolean addNewUserCoupon(long phone) throws Exception {
        List<Coupon> coupons = Coupon.dao.find("select * from user_coupon u where u.type = 1 and  u.tel = " + phone);
        if (coupons == null || coupons.size() <= 0) {
            Coupon byId = Coupon.dao.findById(1);
            if (byId != null) {
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DATE, byId.getInt(Coupon.endDays));
                UserCoupon uc = new UserCoupon();
                uc.set(UserCoupon.createTime, new Timestamp(System.currentTimeMillis()));
                uc.set(UserCoupon.name, byId.get(Coupon.name));
                uc.set(UserCoupon.price, byId.get(Coupon.price));
                uc.set(UserCoupon.tel, phone);
                uc.set(UserCoupon.endTime, new Timestamp(cal.getTimeInMillis()));
                uc.save();
            }
        }
        return true;
    }

    @Override
    public boolean add(UserCoupon coupon) throws Exception {
        return coupon.save();
    }

    @Override
    public boolean delete(long id) throws Exception {
        return UserCoupon.dao.deleteById(id);
    }

    @Override
    public boolean update(UserCoupon coupon) throws Exception {
        return coupon.save();
    }

    @Override
    public UserCoupon findById(long id) throws Exception {
        return UserCoupon.dao.findById(id);
    }

    @Override
    public Page<UserCoupon> findByPage(int pn, int ps,long tel,int isUseful) throws Exception {
        String select = "select *";
        String from = "from user_coupon where tel = '" + tel + "'";
        if(isUseful == 1) {
            from += " and status = 0";
        }
        Object[] param = {};
        return UserCoupon.dao.paginate(pn, ps, select, from, param);
    }

    @Override
    public void useCoupon(long id) throws Exception {
        UserCoupon byId = UserCoupon.dao.findById(id);
        if(byId != null) {
            byId.set(UserCoupon.status, 1);
            byId.update();
        }
    }
}
